package com.chang.order.listener;

import com.chang.order.entity.OrderEntity;
import com.chang.order.service.OrderService;
import com.rabbitmq.client.Channel;
import jakarta.annotation.Resource;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * @author: changzhenxi
 * @date: 2025年03月18日 20:46
 * @Version: 1.0
 * @description:
 */
@Service
@RabbitListener(queues = "order.release.queue")
public class OrderCloseListener {

    @Resource
    OrderService orderService;

    @RabbitHandler
    public void listener(OrderEntity orderEntity, Channel channel, Message message) throws IOException {
        System.out.println("收到过期订单信息，准备关闭订单" + orderEntity.getOrderSn());
        try {
            orderService.closeOrder(orderEntity);
            // 手动调用支付宝收单 防止因为延时问题导致库存解锁之后支付成功的异步通知才收到
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            // 关单异常，拒绝消息
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }
}
